<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Consultation;
use App\Models\ConsultationRecord;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ConsultationController extends Controller {


    //列表
    public function index(Request $request){
        $searchData = $request->post();

        $model = Consultation::orderBy('status')
            ->orderBy('id', 'DESC');

        if ($user_id = $searchData['user_id'] ?? '') {
            $model->where('user_id', 'like', "%{$user_id}%");
        }
        if ($describe = $searchData['describe'] ?? '') {
            $model->where('describe', 'like', "%{$describe}%");
        }

        $result = $model->paginate(config('app.limit'));
        $app_url = config('app.url');
        foreach ($result->items() as $item) {
            $item->nickname = User::whereId($item->user_id)->value('nickname');

            $images = explode(',', $item->images);
            $imgArr = [];
            foreach ($images as $image) {
                $imgArr[] = $app_url . $image;
            }
            $item->images = $imgArr;
        }

        return $this->writeJson(0, [
            'data' => $result->items(),
            'count' => $result->total()
        ]);
    }

    // 回复问诊
    public function reply(Request $request)
    {
        $id = $request->post('id');
        $content = $request->post('content');

        $model = Consultation::find($id);

        $modelR = new ConsultationRecord();
        $modelR->content = $content;
        $modelR->consultation_id = $id;
        $modelR->answer_id = 0;
        $modelR->created_at = now();
        $modelR->save();

        $model->status = 2;
        $model->save();

        return $this->writeJson(0, null, '回复成功');
    }


    //删除
    public function destroy(Request $request){
        $id = (int)$request->post('id',0);
        if(empty($id)){
            return $this->writeJson(1,null,'参数错误');
        }

        try {
            DB::beginTransaction();

            Consultation::destroy($id);
            ConsultationRecord::whereConsultationId($id)->delete();

            DB::commit();
            return $this->writeJson(0, null, '删除成功');
        } catch (\Exception $exception) {
            DB::rollBack();
        } catch (\Throwable $throwable) {
            DB::rollBack();
        }
        return $this->writeJson(1, null, '删除失败');
    }

}
